from rest_framework.views import exception_handler
from rest_framework.response import Response
from utils.common_logger import logger


def common_exception_handler(exc, context):
    request = context.get('request')
    view = context.get('view')
    ip = request.META.get('REMOTE_ADDR')
    try:
        user_id = request.user.pk
    except:
        user_id = '【未登录用户】'
    path = request.get_full_path()
    view_str = str(view)
    res = exception_handler(exc, context)
    logger.error('用户地址为：%s，用户id号为：%s，请求地址为：%s，执行的视图函数为：%s' % (ip, user_id, path, view_str))


    if res:
        # drf的异常,一种是从res.data这个字典的detail中取，一种是  直接取data
        if isinstance(res.data, dict):
            data = {'code': 999, 'msg': res.data.get('detail', '系统错误，请联系系统管理员')}
        else:
            data = {'code': 998, 'msg': res.data}

    else:
        # django的异常
        data = {'code': 888, 'msg': str(exc)}
    return Response(data)
